package com.tn.openrpc.serialization;

import org.apache.commons.codec.binary.Base64;

/**
 * An implementation of <code>Serializer</code> that Base64 encodes/decodes a byte array that represents a serialized
 * object.
 */
public class Base64Serializer implements Serializer<String>
{
  private Serializer<byte[]> byteSerializer;

  /**
   * Creates a new <code>Base64Serializer</code> initialized with the <code>byteSerializer</code> used to
   * serialize/deserialize an object to a byte array.
   */
  public Base64Serializer(Serializer<byte[]> byteSerializer)
  {
    this.byteSerializer = byteSerializer;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String serialize(Object subject) throws SerializationException
  {
    return new Base64().encodeToString(byteSerializer.serialize(subject));
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public <S> S deserialize(String source) throws SerializationException
  {
    //noinspection unchecked
    return (S)byteSerializer.deserialize(new Base64().decode(source));
  }
}
